<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="handleInput"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          node-key="id"
          highlight-current
          :expand-on-click-node="false"
          :data="depts"
          :props="{label: 'name'}"
          default-expand-all
          @current-change="handleCurrentChange"
        />
      </div>

      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push(`/employee/detail`)">添加员工</el-button>

          <el-button size="mini" type="primary" @click="showDialog = true">excel导入</el-button>

          <el-button :loading="loading" size="mini" @click="handleExport">excel导出</el-button>

        </el-row>

        <!-- 表格组件 -->
        <el-table :data="rows">
          <el-table-column align="center" label="头像" prop="staffPhoto">
            <template #default="obj">
              <el-avatar v-if="obj.row.staffPhoto" size="mini" :src="obj.row.staffPhoto" />
              <span v-else class="hhh">{{
                obj.row.username.slice(0,2) ==='黑马' ?
                  obj.row.username.slice(2,3):
                  obj.row.username.slice(0,1)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="obj">
              <span>
                {{ obj.row.formOfEmployment === 1 ? '牛閁' : '䋴閁' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280px">
            <template #default="obj">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${obj.row.id}`)">查看</el-button>

              <el-button size="mini" type="text">角色</el-button>

              <el-button size="mini" type="text">删除</el-button>

            </template>

          </el-table-column>

        </el-table>

        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="page"
            @current-change="handleChange"
          />
        </el-row>

        <!-- 对话框 -->
        <ImportExcle v-model="showDialog" @refresh="getEmployeeList" />

      </div>

    </div>

  </div>

</template>

<script>
import { getDepartments } from '@/api/department'
import { getData, getEmployeeList } from '@/api/employ'
import { transList2TreeData } from '@/utils'
import ImportExcle from '@/views/employee/components/import-excel.vue'
import FileSaver from 'file-saver'
export default {
  name: 'Employee',
  components: {
    ImportExcle
  },
  data() {
    return {
      depts: [],
      loading: false,
      showDialog: false,
      selectId: null, // 选中部门的ID
      total: 0, //
      rows: [],
      page: 1 // 当前页码
      // timer: null// 防抖定时器ID
    }
  },
  created() {
    this.getDepts()
  },
  methods: {
    // 导出
    async handleExport() {
      this.loading = true
      // 等数据加载完成后再关闭
      // 发送请求获取数据
      try {
        const res = await getData()
        FileSaver.saveAs(res, '员工信息.xlsx')// 下载保存文件
      } catch {
        this.$message.error('导出失败')
      } finally {
        // 结束时走这里，无论成败，都有关闭loading
        this.loading = false
      }
      // console.log(res)
    },
    handleInput(val) {
      // 设置防抖，先关定时器，再开定时器
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        // 请求之前重置页码
        this.page = 1
        this.getEmployeeList()
      }, 5000)
    },
    // 分页时触发的事件
    handleChange(val) {
      console.log('Page changed:', val)
      // 修改页码数
      this.page = val
      // 重新获取数据，带上新的页码
      this.getEmployeeList()
    },
    handleCurrentChange(val) {
      console.log(val)
      this.selectId = val.id
      // 重置页码
      this.page = 1
      this.getEmployeeList()// 获取选中部门旗下的员工数据
    },
    async getDepts() {
      const res = await getDepartments()
      // console.log(res)
      this.depts = transList2TreeData(res, 0)
      // 进入页面首先拿传值教育的id,设置最根部组件选中并高亮
      this.selectId = this.depts[0].id
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.selectId)
      })
      this.getEmployeeList()// 获取传值旗下所有员工的数据
    },
    // 获取员工列表
    async getEmployeeList() {
      const res = await getEmployeeList({
        page: this.page,
        pageSize: 5,
        departmentId: this.selectId,
        keyword: this.keyword// 请求带上关键字
      })
      this.total = res.total
      this.rows = res.rows
    }
  }

}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
  .hhh {
  display: inline-block;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #8df;

  text-align: center;
  line-height: 40px;
  color: #fff;
  font-size: 20px;
}
}

</style>
